package com.nova.pro.opengl;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.nova.pro.opengl.render.SampleRender;
import com.nova.pro.opengl.render.SquareRender;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/**
 * Created by Administrator on 2017-11-28.
 *
 * @author kzaxil
 * @since 1.1.0
 */
public class MainActivity extends AppCompatActivity implements GLSurfaceView.Renderer {
    private GLSurfaceView glSurfaceView;
    private SquareRender mRender;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GLSurfaceView glSurfaceView = new GLSurfaceView(this);
        setContentView(glSurfaceView);
        glSurfaceView.setEGLContextClientVersion(3);
        GLSurfaceView.Renderer renderer = new SampleRender();
        glSurfaceView.setRenderer(renderer);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (glSurfaceView != null) glSurfaceView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (glSurfaceView != null) glSurfaceView.onPause();
    }

    /**
     * Render的模式有两种
     * <ol>
     * <li>自动循环模式：{@link GLSurfaceView#RENDERMODE_CONTINUOUSLY}</li>
     * <li>手动控制模式：{@link GLSurfaceView#RENDERMODE_WHEN_DIRTY}</li>
     * </ol>
     * <p>自动循环模式，也就是说GL线程以一定的时间间隔自动的循环调用用户实现的
     * {@link android.opengl.GLSurfaceView.Renderer#onDrawFrame(GL10)}方法进行一帧一帧地绘制</p>
     * <p>手动控制模式，也就是说当用户需要重绘的时候，主动“拉”这个重绘过程，有点类似于
     * {@link View#invalidate()}。当需要重绘时，调用{@link GLSurfaceView#requestRender()}即可</p>
     *
     * @see android.opengl.GLSurfaceView.Renderer#setRenderMode(int)
     */
    private void initGLSurfaceView() {
        glSurfaceView = new GLSurfaceView(this);
        glSurfaceView.setEGLContextClientVersion(2);// OpenGL ES 2.0
        glSurfaceView.setRenderer(this);
        glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1f);// 将背景设置为灰色
        mRender = new SquareRender();
        mRender.onSurfaceCreated(gl, config);
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        GLES20.glViewport(0, 0, width, height);// 设置视图窗口
        mRender.onSurfaceChanged(gl, width, height);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
        mRender.onDrawFrame(gl);
    }
}
